<?php declare(strict_types=1);


namespace App\Api\V2\Controller\Incoming;

use Aliyun\AliSms;
use App\Api\Controllers\BaseController;
use App\Models\ExtensionWorkers;
use App\Models\ExtensionWorkerStores;
use App\Models\SmsConfig;
use App\Models\Store;
use App\Models\User;
use App\Models\WorkerMerchant;
use App\Traits\ResponseTrait;
use BaconQrCode\Renderer\ImageRenderer;
use BaconQrCode\Renderer\RendererStyle\RendererStyle;
use BaconQrCode\Writer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Validator;
use BaconQrCode\Renderer\Image;
use Tymon\JWTAuth\Facades\JWTAuth;

class AuthController extends BaseController
{
    use ResponseTrait;

    //商户短信登录-创建 store_id
    public function sms(Request $request): string
    {
        $worker_phone = $request->post("worker_phone");
        $phone = $request->post("phone");

        $worker = ExtensionWorkers::query()->where("phone", $worker_phone)->first();
        if (empty($worker)) {
            return $this->errorResponse("推广人员不存在");
        }

        $user = User::query()->where("id", $worker->user_id)->first();
        if (empty($user)) {
            return $this->errorResponse("代理商不存在");
        }
        $config_id = $user->config_id;
        //发送"合伙人通知"短信息通知
        $config = SmsConfig::where('type', '18')
            ->where('config_id', $config_id)
            ->first();
        if (!$config) {
            $config = SmsConfig::where('type', '18')
                ->where('config_id', '1234')
                ->first();
        }
        if (empty($config) || empty($config->app_key)) {
            return $this->errorResponse("配置不存在");
        }
        $redis = Redis::connection('amqpQueue');
        $ch = $redis->get("sms:" . $phone);

        if (!empty($ch)) {
            return $this->errorResponse("短信已发送，请5分钟后在试一试");
        }
        $code = rand(000000, 999999);
        $phone = trim($phone);
        $demo = new AliSms($config->app_key, $config->app_secret);

        $response = $demo->sendSms(
            $config->SignName, // 短信签名
            $config->TemplateCode, // 短信模板编号
            $phone, // 短信接收者
            [
                "code" => $code
            ]
        );
        if ($response->Code != 'OK') {
            return $this->errorResponse("发送短信失败");
        }

        $redis->setex("sms:" . $phone, 60 * 5, $code);
        DB::table("sms_worker_logs")->insert([
            "phone" => $phone,
            "code" => $code,
            "created_at" => time(),
            "updated_at" => time()
        ]);

        return $this->successResponse("ok");
    }

    //登录
    public function login(Request $request): string
    {
        //在这里登录
        $worker_phone = $request->post("worker_phone");

        $phone = $request->post("phone");

        $code = $request->post("code", "");
        $is_change = $request->post("is_change", 1);

        $redis = Redis::connection('amqpQueue');
        $redisPhoneCode = $redis->get("sms:" . $phone);
        if (empty($redisPhoneCode)) {
            return $this->errorResponse("请先发送验证码");
        }
        if ($redisPhoneCode != $code) {
            return $this->errorResponse("验证不正确");
        }
        $worker = ExtensionWorkers::query()->where("phone", $worker_phone)->first();
        if (empty($worker)) {
            return $this->errorResponse("推广人员不存在");
        }

        //在这里判断当前手机号是否已经注册了。注册获取store_id
        $store = Store::query()->where("people_phone", $phone)->first();
        if (empty($store)) {
            $store_id = date("YmdHis", time()) . rand(10000000, 99999999);
        } else {
            $store_id = $store->store_id;
            //判断这个店铺是否为该工作人员
            if (empty(ExtensionWorkerStores::query()->where(["worker_id" => $worker->id, "store_id" => $store_id, "phone" => $phone])->first())) {
                return $this->errorResponse("已注册的店铺，不属于该推广人员");
            }
        }

        $user = User::query()->where("id", $worker->user_id)->first();
        if (empty($user)) {
            return $this->errorResponse("代理商不存在");
        }
        $workerMerchant = new WorkerMerchant();
        $workerMerchant->store_id = $store_id;
        $workerMerchant->user_id = $user->id;
        $workerMerchant->wid = $worker->id;
        $workerMerchant->worker_phone = $worker_phone;
        $workerMerchant->phone = $phone;
        //设置token
        $token = JWTAuth::fromUser($workerMerchant);//根据用户得到token
        $redis = Redis::connection('amqpQueue');
        $redis->del(["sms:" . $phone]);

        //记录石佛勾选
        $ch = DB::table("extension_worker_merchant")->where([
            "worker_id" => $worker->id,
            "phone" => $phone,
        ])->first();
        if (empty($ch)) {
            DB::table("extension_worker_merchant")->insert([
                "worker_id" => $worker->id,
                "phone" => $phone,
                "is_change" => $is_change
            ]);
        } else {
            DB::table("extension_worker_merchant")->where([
                "worker_id" => $worker->id,
                "phone" => $phone,
            ])->update([
                "is_change" => $is_change
            ]);
        }
        return $this->successResponse("ok", ["data" => [
            "user_id" => $user->id,
            "worker_phone" => $worker_phone,
            "phone" => $phone,
            "store_id" => $store_id,
            "token" => $token
        ]]);
    }

}